package org.jeecg.modules.hems.regionalmanagement.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.hems.regionalmanagement.entity.BsMapArea;
import org.jeecg.modules.hems.regionalmanagement.service.IBsMapAreaService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;


import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 区域管理
 * @Author: jeecg-boot
 * @Date:   2022-06-27
 * @Version: V1.0
 */
@Api(tags="区域管理")
@RestController
@RequestMapping("/regional/bsMapArea")
@Slf4j
public class BsMapAreaController extends JeecgController<BsMapArea, IBsMapAreaService>{
	@Autowired
	private IBsMapAreaService bsMapAreaService;

	@Value(value="${jeecg.path.upload}")
	private String uploadpath;
	/**
	 * 分页列表查询
	 *
	 * @param bsMapArea
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "区域管理-分页列表查询")
	@ApiOperation(value="区域管理-分页列表查询", notes="区域管理-分页列表查询")
	@GetMapping(value = "/rootList")
	public Result<?> queryPageList(BsMapArea bsMapArea,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String parentId = bsMapArea.getParentId();
		if (oConvertUtils.isEmpty(parentId)) {
			parentId = "0";
		}
		bsMapArea.setParentId(null);
		QueryWrapper<BsMapArea> queryWrapper = QueryGenerator.initQueryWrapper(bsMapArea, req.getParameterMap());
		// 使用 eq 防止模糊查询
		queryWrapper.eq("parent_id", parentId);
		Page<BsMapArea> page = new Page<BsMapArea>(pageNo, pageSize);
		IPage<BsMapArea> pageList = bsMapAreaService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	 /**
      * 获取子数据
      * @param
      * @param req
      * @return
      */
	@AutoLog(value = "区域管理-获取子数据")
	@ApiOperation(value="区域管理-获取子数据", notes="区域管理-获取子数据")
	@GetMapping(value = "/childList")
	public Result<?> queryPageList(BsMapArea bsMapArea,HttpServletRequest req) {
		QueryWrapper<BsMapArea> queryWrapper = QueryGenerator.initQueryWrapper(bsMapArea, req.getParameterMap());
		List<BsMapArea> list = bsMapAreaService.list(queryWrapper);
		IPage<BsMapArea> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
		return Result.ok(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentIds 父ID（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
	@AutoLog(value = "区域管理-批量获取子数据")
    @ApiOperation(value="区域管理-批量获取子数据", notes="区域管理-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<BsMapArea> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("parent_id", parentIdList);
            List<BsMapArea> list = bsMapAreaService.list(queryWrapper);
            IPage<BsMapArea> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.ok(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }
	
	/**
	 *   添加
	 *
	 * @param bsMapArea
	 * @return
	 */
	@AutoLog(value = "区域管理-添加")
	@ApiOperation(value="区域管理-添加", notes="区域管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BsMapArea bsMapArea) {
		bsMapAreaService.addBsMapArea(bsMapArea);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param bsMapArea
	 * @return
	 */
	@AutoLog(value = "区域管理-编辑")
	@ApiOperation(value="区域管理-编辑", notes="区域管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BsMapArea bsMapArea) {
		bsMapAreaService.updateBsMapArea(bsMapArea);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "区域管理-通过id删除")
	@ApiOperation(value="区域管理-通过id删除", notes="区域管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		bsMapAreaService.deleteBsMapArea(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "区域管理-批量删除")
	@ApiOperation(value="区域管理-批量删除", notes="区域管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.bsMapAreaService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "区域管理-通过id查询")
	@ApiOperation(value="区域管理-通过id查询", notes="区域管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BsMapArea bsMapArea = bsMapAreaService.getById(id);
		if(bsMapArea==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(bsMapArea);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param bsMapArea
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BsMapArea bsMapArea) {
		return super.exportXls(request, bsMapArea, BsMapArea.class, "区域管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, BsMapArea.class);
    }
	 /**
	  * 文件统一上传方法
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 @PostMapping(value = "/upload")
	 public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
		 Result<?> result = new Result<>();
		 // 文件存放目录
		 String bizPath = request.getParameter("biz");
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 // 获取上传文件对象
		 MultipartFile file = multipartRequest.getFile("file");
		 String savePath = this.uploadLocal(file, bizPath);
		 if (StringUtils.isNotEmpty(savePath)) {
			 result.setMessage(savePath);
			 result.setSuccess(true);
		 } else {
			 result.setMessage("上传失败！");
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 本地文件上传
	  *
	  * @param mf      文件
	  * @param bizPath 自定义路径
	  * @return
	  */
	 private String uploadLocal(MultipartFile mf, String bizPath) {
		 try {
			 // 本地文件上传存储目录
			 String ctxPath = uploadpath;
			 String fileName = null;
			 File file = new File(ctxPath + File.separator + bizPath + File.separator);
			 if (!file.exists()) {
				 // 创建文件根目录
				 file.mkdirs();
			 }
			 // 获取文件名
			 fileName = this.getFileName(mf);

			 String savePath = file.getPath() + File.separator + fileName;
			 File savefile = new File(savePath);
			 FileCopyUtils.copy(mf.getBytes(), savefile);
			 String dbpath = null;
			 if (StringUtils.isNotBlank(bizPath)) {
				 dbpath = bizPath + File.separator + fileName;
			 } else {
				 dbpath = fileName;
			 }
			 if (dbpath.contains("\\")) {
				 dbpath = dbpath.replace("\\", "/");
			 }
			 return dbpath;
		 } catch (IOException e) {
			 log.error("文件上传失败：", e);
		 }
		 return "";
	 }


	 /**
	  * 获取文件名
	  *
	  * @param file
	  * @return
	  */
	 private String getFileName(MultipartFile file) {
		 String fileName = null;
		 // 获取文件名
		 String orgName = CommonUtils.getFileName(file.getOriginalFilename());
		 if (orgName.indexOf(".") != -1) {
			 fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + orgName.substring(orgName.lastIndexOf("."));
		 } else {
			 fileName = orgName + "_" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
		 }
		 return fileName;
	 }


}
